package com.sync.syncmasterdata.dingtask.service;

import com.aliyun.dingtalktodo_1_0.Client;
import com.aliyun.dingtalktodo_1_0.models.CreateTodoTaskHeaders;
import com.aliyun.dingtalktodo_1_0.models.CreateTodoTaskRequest;
import com.aliyun.dingtalktodo_1_0.models.CreateTodoTaskResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
@Slf4j
public class DingTaskService {

    @Autowired
    private DingTaskUtil dingTaskUtil;

    @Autowired
    private ObjectMapper objectMapper;

    private static String CPTOKEN;

    /**
     * 创建ding 任务
     */
    public void createTask(String unionid,String taskGuid) {
        try {
            log.info("获取到的unionid--{}",unionid);
        CreateTodoTaskHeaders createTodoTaskHeaders = new CreateTodoTaskHeaders();
        createTodoTaskHeaders.xAcsDingtalkAccessToken = regetToken();
        CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs notifyConfigs = new CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs();
        notifyConfigs.setDingNotify("1");
        CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl detailUrl = new CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl();
        detailUrl.setAppUrl("http://www.baidu.com");
        detailUrl.setPcUrl("http://www.baidu.com");
        CreateTodoTaskRequest createTodoTaskRequest = new CreateTodoTaskRequest().setCreatorId(unionid).setSubject("开发推送的测试代办信息").setDescription("这个是开发推送的代办信息\n 20220323的记录").setExecutorIds(Arrays.asList(unionid)).setParticipantIds(Arrays.asList(unionid)).setIsOnlyShowExecutor(true).setPriority(30).setDueTime(System.currentTimeMillis()).setDetailUrl(detailUrl).setSourceId(String.valueOf(System.currentTimeMillis()));

        Config config=new Config();
        config.protocol = "https";
        config.regionId = "central";

            Client client = new Client(config);
            CreateTodoTaskResponse rsq = client.createTodoTaskWithOptions(unionid, createTodoTaskRequest, createTodoTaskHeaders, new RuntimeOptions());
            log.info("rsq--{}", objectMapper.writeValueAsString(rsq.getBody()));
        } catch (TeaException err) {
            log.info("报错异常:code-{};msg-{}", err.code, err.message);

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            log.info("报错异常:code-{};msg-{}", err.code, err.message);

        }

    }

    /**
     * 通过手机号 获取钉钉某用户的unionid
     *
     * @param phone
     * @return
     */
    public String getDingUnionidByPhone(String phone) {
        if (phone == null || phone.equals("")) {
            return null;
        }
        try {
            String access_token = regetToken();
            DingTalkClient clientUserid = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            DingTalkClient clientUnionid = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(phone);
            OapiV2UserGetbymobileResponse rsp = clientUserid.execute(req, access_token);

            if (rsp.getErrcode() == 0) {
                String userid=rsp.getResult().getUserid();
                OapiV2UserGetRequest requnion=new OapiV2UserGetRequest();
                requnion.setUserid(userid);
                OapiV2UserGetResponse rspunion=clientUnionid.execute(requnion,access_token);
                return rspunion.getResult().getUnionid();
            } else {
                log.info("返回异常:{}", rsp.getErrmsg());
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public String regetToken()throws Exception {
        if (StringUtils.isBlank(CPTOKEN)) {
            log.info("regetToken");
            CPTOKEN=this.dingTaskUtil.getCPToken("dingtaskTag");
        }
        return CPTOKEN;
    }
}
